<template>
	<div class="local-api-connector-form">
		<a-form ref="formRef" :model="modelValue" :rules="rules" layout="vertical">
			<!-- API扫描配置 -->
			<a-divider orientation="left">API扫描配置</a-divider>
			<ApiScanConfig ref="apiScanConfigRef" v-model:modelValue="scanConfig" @change="handleScanConfigChange" />

			<!-- 高级配置 -->
			<a-divider orientation="left">高级配置</a-divider>
			<CacheConfig ref="cacheConfigRef" v-model:modelValue="cacheConfig" @change="handleCacheConfigChange" />
		</a-form>

		<!-- 连接测试 -->
		<a-divider />
		<a-space>
			<a-button :loading="testing" type="primary" @click="testConnection">
				<template #icon>
					<CheckCircleOutlined />
				</template>
				测试连接
			</a-button>
			<!-- API预览 -->
			<ApiPreview ref="apiPreviewRef" :connectorConfig="{ ...scanConfig, ...cacheConfig }" />
		</a-space>
	</div>
</template>

<script setup>
	import { ref, reactive, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { CheckCircleOutlined } from '@ant-design/icons-vue'
	import dataConnectorApi from '@/views/plugin/dashboard/api/dataConnectorApi'
	import ApiScanConfig from './components/ApiScanConfig.vue'
	import CacheConfig from './components/CacheConfig.vue'
	import ApiPreview from './components/ApiPreview.vue'

	// Props
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})
	console.log(props.modelValue)

	// Emits
	const emit = defineEmits(['change', 'change'])

	// 表单引用
	const formRef = ref()
	const apiScanConfigRef = ref()
	const cacheConfigRef = ref()
	const apiPreviewRef = ref()

	// 表单验证规则
	const rules = {}

	// 获取配置数据的辅助函数
	const getConfigValue = (key, defaultValue) => {
		const config = props.modelValue || {}
		return config[key] || defaultValue
	}

	// 配置数据
	let scanConfig = reactive({
		scanModules: getConfigValue('scanModules', '["dashboard", "sys"]'),
		onlyGetMethods: getConfigValue('onlyGetMethods', 'true'),
		enablePermissionCheck: getConfigValue('enablePermissionCheck', 'true'),
		excludeSystemApis: getConfigValue('excludeSystemApis', 'true'),
		excludePaths: getConfigValue('excludePaths', '[]')
	})

	let cacheConfig = reactive({
		enableCache: getConfigValue('enableCache', 'true'),
		cacheTimeout: getConfigValue('cacheTimeout', '300')
	})

	// 测试状态
	const testing = ref(false)

	// 监听配置变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal.config) {
				const config = newVal.config

				Object.assign(scanConfig, {
					scanModules: config.scanModules || '["dashboard", "sys"]',
					onlyGetMethods: config.onlyGetMethods || 'true',
					enablePermissionCheck: config.enablePermissionCheck || 'true',
					excludeSystemApis: config.excludeSystemApis || 'true',
					excludePaths: config.excludePaths || '[]'
				})

				Object.assign(cacheConfig, {
					enableCache: config.enableCache || 'true',
					cacheTimeout: config.cacheTimeout || '300'
				})
			}
		},
		{ deep: true, immediate: true }
	)

	// 更新配置
	const updateConfig = () => {
		const config = {
			...scanConfig,
			...cacheConfig
		}

		const updatedValue = {
			...props.modelValue,
			config
		}
		emit('change', updatedValue)
	}

	// 处理扫描配置变化
	const handleScanConfigChange = (config) => {
		Object.assign(scanConfig, config)
		console.log(scanConfig)
		updateConfig()
	}

	// 处理缓存配置变化
	const handleCacheConfigChange = (config) => {
		Object.assign(cacheConfig, config)
		updateConfig()
	}

	// 测试连接
	const testConnection = async () => {
		try {
			testing.value = true

			// 构建测试配置
			const testConfig = {
				type: 'LOCAL_API',
				config: {
					...scanConfig,
					...cacheConfig
				}
			}

			await dataConnectorApi.testConnection(testConfig)
			message.success('本地API连接器测试成功！')
		} catch (error) {
			console.error('连接测试失败:', error)
			message.error('连接测试失败：' + (error.message || '未知错误'))
		} finally {
			testing.value = false
		}
	}

	// 表单验证
	const validate = async () => {
		try {
			await formRef.value.validate()

			// 验证子组件
			if (apiScanConfigRef.value?.validateConfig) {
				const scanValidation = apiScanConfigRef.value.validateConfig()
				if (!scanValidation.valid) {
					message.error(scanValidation.message)
					return false
				}
			}

			if (cacheConfigRef.value?.validateConfig) {
				const cacheValidation = cacheConfigRef.value.validateConfig()
				if (!cacheValidation.valid) {
					message.error(cacheValidation.message)
					return false
				}
			}

			return true
		} catch (error) {
			return false
		}
	}

	// 暴露方法给父组件
	defineExpose({
		validate
	})
</script>

<style scoped>
	.local-api-connector-form {
		padding: 16px;
	}

	.form-help-text {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
	}

	:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
		margin: 16px 0;
	}

	:deep(.ant-checkbox-group) {
		width: 100%;
	}

	:deep(.ant-col) {
		margin-bottom: 8px;
	}
</style>
